<template>
  <div :style="`width:${!showMobileIcon ? '100%' : ''}`">
    <template v-if="!showMobileIcon">
      <div :class="{'mobile-input-component':showMobilePage && lineFeed}" class="select-input-component">
        <div class="filter-input">
          <el-autocomplete
            v-if="selectKeyToName === '账号' && isSearchResource"
            v-model.trim="value[selectKey]"
            :maxlength="selectKeyToItem.maxlength || 500"
            :fetch-suggestions="querySuggestions"
            :trigger-on-focus="false"
            clearable
            size="small"
            placeholder="请输入内容"
            class="input-width-select input-width-select-bg"
            @select="handleSelectSuggestions"
            @clear="queryClick"
            @keyup.enter.native="queryClick">
            <el-select slot="prepend" v-model="selectKey" size="small" placeholder="请选择" class="changeStatus" popper-class="global-select-down" @change="normalChange" >
              <template v-for="item in filterList">
                <el-option
                  v-if="item.type === 'input'"
                  :key="item.keyword"
                  :label="item.name"
                  :value="item.keyword" />
              </template>
            </el-select>
            <div slot="append" class="filter-input-search" @click="queryClick">
              <i class="el-icon-search"/>
            </div>
            <template slot-scope="{ item }">
              <ToolTip v-if="item.value.length > 13" :content="item.value" placement="right" />
              <div v-else>{{ item.value }}</div>
            </template>
          </el-autocomplete>
          <el-input
            v-else
            v-model.trim="value[selectKey]"
            :maxlength="selectKeyToItem.maxlength || 500"
            :class="{'select-input-focus':inputFocus}"
            clearable
            size="small"
            placeholder="请输入内容"
            class="input-width-select input-width-select-bg"
            @focus="inputFocus = true"
            @blur="inputFocus = false"
            @clear="queryClick"
            @keyup.enter.native="queryClick">
            <el-select slot="prepend" v-model="selectKey" size="small" placeholder="请选择" class="changeStatus" popper-class="global-select-down" @change="normalChange" >
              <template v-for="item in filterList">
                <el-option
                  v-if="item.type === 'input'"
                  :key="item.keyword"
                  :label="item.name"
                  :value="item.keyword" />
              </template>
            </el-select>
            <div slot="append" class="filter-input-search" @click="queryClick">
              <i class="el-icon-search"/>
            </div>
          </el-input>
        </div>
        <div v-if="showAdvancedFilter" class="operate-btn" @click="changeLevel">
          <!-- 高级 -->
          <el-tooltip :open-delay="500" content="高级筛选" placement="top">
            <div class="filter-box">
              <img :src="advancedFilterIcon" class="operate-icon" alt="">
              <span class="filter-label">高级</span>
            </div>
          </el-tooltip>
        </div>
        <PresetFilter
          v-if="isShowConfig"
          ref="PresetFilterRef"
          :select-value-result="selectValueResult"
          :get-preset-filter="getPresetFilter"
          :preset-type="presetType"
          :open-high-mode="changeLevel"
          use-scope-slot
          @queryClick="queryClick"
          @createNew="createNew" >
          <template slot-scope="scope" >
            <div :class="{'active': scope.visible}" class="operate-btn">
              <!-- 快捷筛选 -->
              <el-tooltip :open-delay="500" content="快捷筛选" placement="top">
                <div class="filter-box">
                  <img :src="scope.visible?presetFilterIconActive:presetFilterIcon" class="operate-icon" alt="">
                  <span class="filter-label">快速</span>
                </div>
              </el-tooltip>
            </div>
          </template>
        </PresetFilter>
        <div v-if="showReset" class="operate-btn" @click="queryEmpty">
          <el-tooltip :open-delay="500" content="重置筛选" placement="top">
            <div class="filter-box">
              <img :src="resetFilterIcon" class="operate-icon" alt="">
              <span class="filter-label">重置</span>
            </div>
          </el-tooltip>
        </div>
        <slot name="input-after"/>
      </div>
      <div class="content">
        <template v-if="showFilterTag">
          <div class="tag-container">
            <template v-for="(item, index) in selectValueResult">
              <el-tag v-if="index <= 2" :key="index" class="filter-tag-group" type="info" disable-transitions>
                <div class="flex">
                  <span class="input-name">{{ item.isExcludeKey ? `${item.name}(不包含)` : item.name }}：</span>
                  <ToolTip :content="item.value" style="max-width: 12em" />
                  <div class="filter-tag-close" @click="deleteTag(item, $event)">
                    <i class="el-tag__close el-icon-close" />
                  </div>
                </div>
              </el-tag>
            </template>
            <div class="filter-icon">
              <div v-if="selectValueResult.length && selectValueResult.length > 3" class="selected" @click="changeLevel">+{{ selectValueResult.length - 3 }}</div>
              <ToolTip v-if="isShowConfig" :show-copy-btn="false" content="保存快捷筛选" style="margin-left: 10px;">
                <div class="filter-icon-container" @click="setPresetFilter"><img :src="filterSaveIcon" alt=""></div>
              </ToolTip>
            </div>
          </div>
        </template>
      </div>
    </template>
    <div v-else class="mobile-icon" @click="changeLevel">
      <el-image :src="mobileIcon" class="img"/>
      <span v-if="showText" class="text">筛选</span>
    </div>
    <FilterDialog
      ref="filterDialogRef"
      v-model="value"
      :drawer-size="drawerSize"
      :visible.sync="showFilterDialog"
      :filter-list="filterList"
      :date-filter-list="dateFilterList"
      :input-filter-list="inputFilterList"
      :select-filter-list="selectFilterList"
      :multi-month-filter-list="multiMonthFilterList"
      :append-to-body="appendToBody"
      :real-time-filter="realTimeFilter"
      :is-show-config="isShowConfig"
      :select-value-result="selectValueResult"
      :custom-filter-list="customFilterList"
      :custom-class="customClass"
      :extra-filter-list="extraFilterList"
      :preset-type="presetType"
      @drawerHide="onDrawerHide"
      @queryEmpty="queryEmpty"
      @queryClick="queryClick"
      @datePickerTime="datePickerTime"
      @submitMonths="submitMonths"
      @resetMonths="resetMonths"
      @selectChange="selectChange"
      @loadMoreFilter="loadMoreFilter"
      @createNew="createNew"
    >
      <div slot="middleContentPlaceholder">
        <slot name="middleContent"/>
      </div>
      <div slot="selectAfterPlaceholder">
        <slot name="selectAfter" />
      </div>
      <div slot="checkGroup" >
        <slot name="checkGroup" />
      </div>
      <template slot="appendBox" slot-scope="data">
        <slot :keyword="data.keyword" name="valueAppend" />
      </template>
    </FilterDialog>
  </div>
</template>

<script>
import clearIcon from '@/assets/medium/clear.png';
import highlvIcon from '@/assets/orderlist/highlv.png';
import mobileIcon from '@/assets/mobileIcon/search.png';
import { getResource } from '@/api/select';

import { format } from '@/filters/date';
import filterInput from './input';
import filterSelect from './select';
import filterDate from './date';
import FilterDialog from './module/filterDialog';
import PresetFilter from './module/PresetFilter/index.vue';
import { numberTextFormat } from '@/filters/number';
import { mapState } from 'vuex';
// img
import advancedFilterIcon from '@/assets/setting/filter.png';
import advancedFilterIconActive from '@/assets/setting/advancedFilter_active.png';
import presetFilterIcon from '@/assets/setting/quick.png';
import presetFilterIconActive from '@/assets/setting/quick_active.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import filterNumIcon from '@/assets/setting/filterNum.png';
import filterSaveIcon from '@/assets/setting/filterSave.png';

export default {
  name: 'FilterInput',
  components: { filterInput, filterSelect, filterDate, FilterDialog, PresetFilter },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  provide() {
    return {
      setPresetVal: (val) => {
        this.$emit('changeValue', val);
      }
    };
  },
  props: {
    defaultSelectKey: { // 默认选中的key
      type: String,
      default: ''
    },
    appendToBody: {
      type: Boolean,
      default: true
    },
    value: {
      type: Object,
      default: () => {
        return {};
      }
    },
    showSearchBtn: {
      type: Boolean,
      default: false
    },
    showAdvancedFilter: { // 是否展示高级按钮
      type: Boolean,
      default: true
    },
    showReset: {
      type: Boolean,
      default: true
    },
    isSearchResource: { // 是否把账号的输入框变成建议搜索
      type: Boolean,
      default: false
    },
    customFilterList: {
      type: Array,
      default: () => []
    },
    customFilterData: {
      type: Array,
      default: () => []
    },
    drawerSize: {
      type: Number,
      default: 0
    },
    /**
     * filterList
     * @param keyword 字段名
     * @param name 名称
     * @param type 类型,只有input才会出现在普通状态（input、select、date、rangeDate、complexRangeDate、multiMonth）
     * @param options  类型为select或complexRangeDate时使用，下拉选项
     * @param format 类型为rangeDate、date、complexRangeDate时使用，时间格式，默认 yyyy/MM/dd
     * @param timeTypeKeyword 类型为complexRangeDate时，代表下拉选项的字段名称
     * @param tagName 类型为inputSearch时，代表需要被赋值筛选标签的key
    */
    filterList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    realTimeFilter: { // 实时查询
      type: Boolean,
      default: false
    },
    isSingleCondition: {// 限制下拉输入单一条件搜索
      type: Boolean,
      default: false
    },
    showMobileIcon: {// 列表移动端仅展示图标
      type: Boolean,
      default: false
    },
    lineFeed: {// 搜索框与按钮换行展示
      type: Boolean,
      default: false
    },
    isShowConfig: { // 是否可以快捷筛选条件
      type: Boolean,
      default: false
    },
    customClass: {
      type: String,
      default: ''
    },
    showText: {
      type: Boolean,
      default: true
    },
    extraFilterList: {
      type: Array,
      default: () => []
    },
    presetType: { // 预设选项类型, 1-资源, 2-微博效果
      type: Number,
      default: 0
    },
    jumpSetParams: { // 从飞书跳转过来的勾选参数
      type: Object,
      default: null
    }
  },
  data() {
    let selectKey = this.defaultSelectKey || '';
    if (!selectKey) {
      for (let i = 0; i < this.filterList.length; i++) {
        if (this.filterList[i].type === 'input') {
          selectKey = this.filterList[i].keyword;
          break;
        }
      }
    }
    return {
      mobileIcon, advancedFilterIcon, advancedFilterIconActive,
      filterSaveIcon, filterNumIcon,
      presetFilterIcon, presetFilterIconActive,
      resetFilterIcon,
      clearIcon, highlvIcon,
      selectKey: selectKey,
      paramsObj: {},
      rangeDateTime: [],
      highOptions: false,
      showFilterDialog: false,
      inputFocus: false,
      cache: {},
      isInitFilterConfig: false,
      hasDefaultPresetFilter: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'filterConfig': state => state.filter.filterConfig
    }),
    dateFilterList() {
      const typeArr = ['date', 'rangeDate', 'complexRangeDate', 'conditionSelect'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) {
          return i;
        }
      }).filter(i => !!i);
    },
    inputFilterList() {
      const typeArr = ['input', 'inputRange', 'inputSearch', 'conditionInput'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) { return i; }
      }).filter(i => !!i);
    },
    selectFilterList() {
      const typeArr = ['select', 'cascaderSelectWithChild', 'cascaderSelect', 'mulSelect', 'loadMoreSelect', 'regionSelect', 'addressSelect'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) { return i; }
      }).filter(i => !!i);
    },
    multiMonthFilterList() {
      return this.filterList.filter(i => i.type === 'multiMonth');
    },
    showFilterTag() {
      const selectValueResult = this.selectValueResult;
      const tagShowStatus = !!(selectValueResult.length && !(selectValueResult.length === 1 && selectValueResult[0].key === this.selectKey));
      this.$emit('filterTagStatus', tagShowStatus);
      return tagShowStatus;
    },
    selectKeyToName() {
      const selectKey = this.selectKey;
      const res = this.filterList.filter(i => {
        return i.keyword === selectKey;
      });
      return res && res[0] && res[0].name ? res[0].name : '';
    },
    selectKeyToItem() {
      const selectKey = this.selectKey;
      const res = this.filterList.find(i => {
        return i.keyword === selectKey;
      });
      return res || {};
    },
    selectValueResult() {
      const result = [];
      for (const key in this.value) {
        if ((this.value[key] && this.value[key] !== '') || this.value[key] === 0 || this.value[key] === false) {
          if (!(this.value[key] instanceof Array && this.value[key].length === 0)) {
            const obj = this.getHighLevelTag(key, this.value[key], this.value);
            if (`${key}Equal` in this.value) {
              obj.isExcludeKey = !this.value[`${key}Equal`];
            }
            if (obj)result.push(obj);
          }
        }
      }
      const customFilterCopy = JSON.parse(JSON.stringify(this.customFilterList));
      // 排除母婴联动过滤项
      const customFilter = customFilterCopy.filter(item => item.key !== 'birthday' && item.key !== 'sex' && item.key !== 'babPrice');
      customFilter.forEach(item => {
        const curFilterData = this.customFilterData.filter(_item => item.key === _item.key);
        item.name = curFilterData && curFilterData.length ? curFilterData[0].label : '';
        item.isCustom = true;
        const numberTypeKeys = ['price', 'fansNum', 'babPrice', 'averageReadNum', 'averageInteractiveNum', 'exposure', 'averagePlayNum', 'averageOnlinePlay', 'likesNum'];
        const selectTypeKeys = ['accountBelong', 'isExpire', 'operateMode', 'pingtai', 'adType', 'additional', 'tag'];
        if (numberTypeKeys.includes(item.key)) {
          if (item.start && !item.end) {
            item.value = `${this.setPrice(item.start, item.key)}以上`;
          } else if ((item.start === '0' || item.start === 0 || !item.start) && item.end) {
            item.value = `${this.setPrice(item.end, item.key)}以下`;
          } else {
            item.value = `${this.setPrice(item.start, item.key)}-${this.setPrice(item.end, item.key)}`;
          }
        }
        if (selectTypeKeys.includes(item.key)) {
          const values = [];
          item.value.split(',').forEach(selectValue => {
            const selectData = curFilterData[0].valueList.filter(valueItem => selectValue === valueItem.key.toString());
            values.push(selectData[0].label);
          });
          item.value = values.join(',');
        }
      });
      return result.concat(customFilter);
    }
  },
  inject: {
    setFilterParams: { default: null },
    getActiveTabs: { default: null }
  },
  watch: {
    defaultSelectKey: {
      handler(newVal) {
        if (newVal) {
          this.selectKey = newVal;
        }
      },
      immediate: true
    },
    filterConfig: {
      handler() {
        if (this.isShowConfig && !this.isInitFilterConfig) {
          this.isInitFilterConfig = true;
          this.presetFilterDefault();
        }
      },
      immediate: true
    }
  },
  methods: {
    setPrice(number, key) {
      if (!number) return 0;
      const formatNumberKeys = ['price', 'babPrice'];
      const numberPrice = formatNumberKeys.includes(key) ? Number(number) / 100 : Number(number);
      if (numberPrice < 10000) return `${numberPrice}${key === 'price' ? '元' : ''}`;
      return numberTextFormat(numberPrice, 1);
    },
    loadMoreFilter(data) {
      this.$emit('loadMoreFilter', data);
    },
    createNew() {
      this.queryEmpty();
      if (this.$refs.PresetFilterRef) {
        this.$refs.PresetFilterRef.visible = false;
      }
      this.showFilterDialog = true;
    },
    // 事件触发
    inputChange() {
      this.$emit('changeValue', this.value);
      this.$emit('handelClick');
    },
    selectChange({ value, item, selectedItems }) {
      this.$emit('selectChange', { value, item, selectedItems });
      if (item.type === 'loadMoreSelect' && !item.multiple) {
        this.cache[item.keyword] = JSON.parse(JSON.stringify(item));
      }
      this.realTimeQueryClick();
      this.$emit('changeValue', this.value);
    },
    realTimeQueryClick() {
      this.realTimeFilter && this.queryClick();
    },
    onDrawerHide() {
      this.showFilterDialog = false;
      // !this.realTimeFilter && this.queryClick();
    },
    queryClick(val) {
      this.$emit('handelClick');
    },
    resetMonthData() {
      if (this.$refs.filterDialogRef.$refs.multiRef) {
        this.$refs.filterDialogRef.$refs.multiRef[0].handleCancel();
      }
    },
    queryEmpty() {
      let selectKey = '';
      for (let i = 0; i < this.filterList.length; i++) {
        if (this.filterList[i].type === 'input') {
          selectKey = this.filterList[i].keyword;
          break;
        }
      }
      this.selectKey = selectKey;
      this.$emit('queryEmpty');
      this.resetMonthData();
    },
    datePickerTime({ val, key }) {
      if (!val) {
        delete this.value[key];
      }
      this.$emit('changeValue', this.value);
      this.realTimeQueryClick();
    },
    submitMonths({ val, key }) {
      if (!val) {
        delete this.value[key];
      }
      this.$emit('changeValue', this.value);
    },
    resetMonths() {
      delete this.value['months'];
      this.$emit('changeValue', this.value);
    },
    // 操作
    deleteTag(data, e) {
      const { key } = data;
      e.stopPropagation();
      this.value[key] = '';
      if (data.isExcludeKey) {
        delete this.value[`${key}Equal`];
      }
      if (data.isCustom) {
        const curHandleData = this.customFilterData.filter(item => item.key === data.key);
        this.$emit('customTagDel', curHandleData[0]);
      } else {
        this.$emit('deleteTagBefore', key);
        this.queryClick();
      }
    },
    changeLevel() {
      this.level = this.level === 'normal' ? 'high' : 'normal';
      this.showFilterDialog = true;
      this.$refs['filterDialogRef'].setFilterVal();
    },
    normalChange() {
      if (this.isSingleCondition) {
        this.value = {};
      }
      this.$emit('changeValue', this.value);
    },
    findKeyType(key) {
      const item = this.filterList.find(i => {
        return i.keyword === key;
      });
      return item ? item.type : '';
    },
    changeSelectKey() {
      for (let i = 0; i < this.filterList.length; i++) {
        if (this.filterList[i].type === 'input') {
          this.selectKey = this.filterList[i].keyword;
          break;
        }
      }
    },
    // 工具方法
    getName(key) {
      const current = this.filterList.find(i => i.keyword === key);
      return current ? current.name : '';
    },
    findOptions(options, value, valueName = 'id', childrenVal = 'item') {
      const callback = (opt, val) => {
        if (opt && opt.length === 0) return null;
        for (let i = 0; i < opt.length; i++) {
          if (opt[i][valueName] === val) {
            return opt[i];
          } else if (opt[i][childrenVal]) {
            const res = callback(opt[i][childrenVal], val);
            if (res) {
              return res;
            }
          }
        }
      };
      const a = callback(options, value);
      return a;
    },
    // 设置tag展示规则
    getHighLevelTag(key, value, valueObj) {
      try {
        let list = this.filterList;
        if (this.extraFilterList && this.extraFilterList.length) {
          this.extraFilterList.map(it => {
            if (it.filterList) list = [...list, ...it.filterList];
          });
        }
        const current = list.find(i => i.keyword === key);
        if (!current) return null;
        const { type, selectType, options, name, labelName, multiple, valueName, timeTypeKeyword, childrenVal, directShow, labelUnit, separator } = current;
        if (directShow) {
          return { name, key, value: value.join(',') };
        }
        // if (type === 'conditionInput' || type === 'conditionSelect') {
        //   console.log({ name, key, value, isExcludeKey: !this.value[excludeKey] }, '---');
        //   return { name, key, value, isExcludeKey: !this.value[excludeKey] };
        // }
        if (type === 'select' || selectType === 'select') {
          const tempValKey = valueName || 'value';
          const tempLabelKey = labelName || 'label';
          const opt = options.find(i => i[tempValKey] === value);
          return opt ? { name, key, value: opt[tempLabelKey] } : { name, key, value };
        } else if (type === 'loadMoreSelect' || selectType === 'loadMoreSelect') {
          if (multiple) {
            return { name, key, value: value.join(',') };
          }
          if (current._showValue) {
            return { name, key, value: current._showValue || value };
          }
          const cache = this.cache[current.keyword];
          return { name, key, value: cache && cache._showValue || value };
          // const opt = options.find(i => i[valueName] === value);
          // return opt ? { name, key, value: opt[labelName] } : { key, value };
        } else if (type === 'mulSelect' || selectType === 'mulSelect' || (type !== 'cascaderSelect' && multiple)) {
          // 多选有远程下拉多选的类型
          const target = [];
          const optionsList = options;
          const label = labelName || 'label';
          const keyName = valueName || 'value';
          if (!value) return;
          value.forEach(val => {
            const opt = optionsList.find(i => i[keyName] === val);
            opt && target.push(opt[label]);
          });
          if (target.length > 0) {
            return { name, key, value: target.join(',') };
          } else {
            return null;
          }
        } else if (type === 'cascaderSelect' || selectType === 'cascaderSelect' || type === 'cascaderSelectWithChild' || selectType === 'cascaderSelectWithChild') {
          const target = [];
          if (!value) return;
          if (Array.isArray(value)) {
            if (value.length && Array.isArray(value[0])) {
              value.forEach(item => {
                const temp = item.reduce((pre, cur) => {
                  const opt = this.findOptions(options, cur, valueName, childrenVal);
                  if (opt) {
                    return pre + '-' + cur;
                  }
                });
                if (temp) target.push(temp);
              });
              if (target.length > 0) {
                return { name, key, value: target.join(separator || ',') };
              } else {
                return null;
              }
            } else {
              value.forEach(val => {
                const opt = this.findOptions(options, val, valueName, childrenVal);
                if (opt) target.push(opt[labelName || 'name']);
              });
              if (target.length > 0) {
                return { name, key, value: target.join(separator || ',') };
              } else {
                return null;
              }
            }
          } else {
            const opt = this.findOptions(options, value, valueName, childrenVal);
            return opt ? { name, key, value: opt[labelName || 'name'] } : { key, value };
          }
        } else if (type === 'rangeDate') {
          let curFormat = '';
          if (current.format) {
            const arr = current.format.split(' ');
            curFormat = arr[0].toUpperCase() + `${arr[1] ? ' ' + arr[1] : ''}`;
          }
          curFormat = curFormat || 'YYYY/MM/DD';
          const dateName = format(value[0], curFormat, true) + '到' + format(value[1], curFormat, true);
          return { name, key, value: dateName };
        } else if (type === 'complexRangeDate') {
          if (this.value[timeTypeKeyword] || this.value[timeTypeKeyword] === 0) {
            const title = options.find(i => i.value === this.value[timeTypeKeyword]);
            const dateName = title.label + format(value[0], 'YYYY/MM/DD') + '到' + format(value[1], 'YYYY/MM/DD');
            return { name, key, value: dateName };
          }
          return null;
        } else if (type === 'inputRange') {
          const hasVal = value && Array.isArray(value) && value.length === 2 && ((value[0] || value[0] === 0) || (value[1] || value[1] === 0));
          let valueLabel = '';
          if (hasVal) {
            if ((value[0] || value[0] === 0) && (value[1] || value[1] === 0)) {
              const cloneVal = JSON.parse(JSON.stringify(value));
              if (labelUnit) {
                if (cloneVal[0] !== 0) cloneVal[0] += labelUnit;
                if (cloneVal[1] !== 0) cloneVal[1] += labelUnit;
              }
              valueLabel = cloneVal.join('-');
            } else if (!value[0] && value[0] !== 0) {
              valueLabel = `<= ${value[1]}${labelUnit || ''}`;
            } else {
              valueLabel = `>= ${value[0]}${labelUnit || ''}`;
            }
          }
          if (valueLabel) return { name, key, value: valueLabel };
          return null;
        } else if (type === 'inputSearch') {
          return { name, key, value: valueObj[current.tagName] };
        }
        return { name, key, value };
      } catch (err) {
        console.log(err);
      }
    },
    isObjEmpty(obj) {
      let empty = true;
      for (const key in obj) {
        const current = this.filterList.find(i => i.keyword === key);
        if (current && ((obj[key] && obj[key] !== '') || obj[key] === 0)) empty = false;
      }
      return JSON.stringify(obj) === '{}' || empty;
    },
    // 输入建议
    querySuggestions(queryString, cb) {
      getResource({ platformId: '', page: 1, perPage: 10, resourceName: queryString }).then(res => {
        if (res.code === 200 && res.data && res.data.items) {
          const result = res.data.items.map(i => {
            const value = `${i.value}${i.historyResourceName ? '（历史：' + i.historyResourceName + '）' : ''}`;
            return {
              label: i.value,
              value: value
            };
          });
          cb(result);
        } else {
          cb([]);
        }
      }).catch(() => {
        cb([]);
      });
    },
    handleSelectSuggestions(item) {
      this.value[this.selectKey] = item.label;
    },
    // 筛选默认条件
    presetFilterDefault() {
      if (this.showMobilePage) return;
      let routeName = this.$route.name;
      if (routeName === 'approvalList') {
        const moduleId = this.$route.params.id;
        routeName = routeName + moduleId;
      }
      if (!this.filterConfig || !this.filterConfig[routeName]) return [];
      // 资源列表页面，需要区分tab
      const activeTabs = this.getActiveTabs ? this.getActiveTabs() : null;
      const curDefaultConfig = this.filterConfig[routeName].find(i => {
        if (this.getActiveTabs) {
          return (!i.activeTabs || i.activeTabs === activeTabs) && i.default;
        }
        return i.default;
      });
      if (!curDefaultConfig) return;
      if (this.setFilterParams) {
        // 如果是资源列表
        this.setFilterParams(curDefaultConfig);
      } else {
        // 其他页面
        this.$nextTick(() => {
          const params = _.cloneDeep(curDefaultConfig.params);
          // 如果列表页有默认筛选,且有从飞书跳转过来的勾选参数,则需赋值给params,否则勾选参数会被覆盖
          if (this.jumpSetParams && Object.keys(this.jumpSetParams).length > 0) {
            for (const key in this.jumpSetParams) {
              params[key] = this.jumpSetParams[key];
            }
          }
          this.$emit('changeValue', params);
        });
      }
      this.hasDefaultPresetFilter = true;
      // 请求查询接口
      this.$nextTick(() => {
        this.queryClick();
      });
    },
    getPresetFilter() {
      return {
        value: this.value,
        filterParams: this.customFilterList
      };
    },
    setPresetFilter() {
      if (this.$refs.PresetFilterRef) {
        this.$refs.PresetFilterRef.setData();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.select-input-component {
  @include flexStyle($align: center);
  &::v-deep {
    .input-width-select-bg {
      &> .el-input__inner {
        background-color: #fff;
      }
    }
    .el-tag.el-tag--info {
      color: #406eff !important;
      background: #eff3fb;
      height: 100%;
      font-size: 12px;
      position: relative;
      max-width: 100%;
      overflow: hidden;
      // .el-icon-close {
      //   position: absolute;
      //   right: 0;
      //   top: 50%;
      //   margin-top: -8px;
      //   background-color: #e4e4e4;
      //   z-index: 2;
      // }
    }
    .el-input-group__append {
      border-left: 1px solid #406EFF;
      border-color: #406EFF;
      padding: 0;
      margin: 0;
      width: 54px;
      overflow: hidden;
      background-color: #406EFF;
      .filter-input-search {
        @include flexStyle(center, center);
        border-radius: 0px;
        border: none;
        padding: 0;
        width: 54px;
        height: 30px;
        cursor: pointer;
        .el-icon-search {
          font-size:16px;
          color: #fff;
        }
      }
    }
    .el-input {
      &>.el-input__inner {
        width: 210px;
      }
    }
    .el-input-group__prepend {
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      .el-input  {
        .el-input__inner {
          padding-left: 8px;
          border: none;
          width: 115px !important;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
}
.mobile-input-component {
  flex-wrap: wrap;
  .filter-input {
    width: 100%;
    margin-bottom: 12px;
    ::v-deep .el-input__inner {
      width: 100%;
    }
  }
}
.mobile-icon {
  @include flexStyle($align: center, $direction: column);
  margin-right: 24px;
  .text {
    font-size: 10px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #aeb6c7;
    line-height: 14px;
    margin-top: 2px;
  }
  .img{
    width: 24px;
    height: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.flex {
  @include flexStyle($align: center);
  height: 100%;
  .input-name {
    @include flexStyle($align: center);
    height: 100%;
  }
}
.high-lv {
  cursor: pointer;
  font-size: 14px;
  flex-shrink: 0;
  margin-left: 12px;
  @include flexStyle($align: center);
  color: #141C3D;
  font-weight: 550;
  &.active {
    color: #406EFF;
  }
  img {
    width: 16px;
    margin-right: 3px;
  }
  i {
    margin-left:5px;
    color: #406EFF;
  }
}
.high-mode {
  @include flexStyle();
  height: 32px;
  overflow: hidden;
  .filter-input__prepend {
    @include flexStyle($align: center);
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    border: 1px solid #DDDDDD;
    border-right: none;
    flex-shrink: 0;
    height: 100%;
    padding: 0 8px;
    font-size: 14px;
    background-color: #fff;
    color: #606266;
    width: 116px;
  }
  .filter-input__apend {
    border:1px solid #406EFF;
    background: #406EFF;
    padding: 0;
    height: 32px;
    cursor: pointer;
    width: 56px;
    @include flexStyle($align: center, $justify:center);
    border-radius: 0px;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    .el-icon-search {
      font-size:16px;
      color: #fff;
    }
  }
  .filter-input__input {
    padding: 2px 10px;
    border: 1px solid #DDDDDD;
    cursor: pointer;
    width: 210px;
    overflow: hidden;
    height: 100%;
    background: #fff;
    @include flexStyle();
    // align-items: center;
    &::v-deep {
      .el-tag {
        &:hover {
          .filter-tag-close {
            @include flexStyle();
          }
        }
      }
    }
    .content {
      width: 100%;
      overflow: hidden;
    }
    .placeholder {
      color: #ccc;
      font-size: 13px;
      height: 100%;
      display: flex;
      align-items: center;
    }
  }
}

.tag-container {
  height: 100%;
  display: flex;
  align-items: center;
  margin-top: 8px;
  .filter-icon {
    height: 100%;
    display: flex;
    align-items: center;
    .selected {
      color: #406EFF;
      cursor: pointer;
      height: 24px;
      line-height: 24px;
      background-color: #eff4ff;
      padding: 0 8px;
      border-radius: 4px;
    }
  }
  .filter-icon-container {
    width: 24px;
    height: 24px;
    background: #f3f5fa;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    img {
      width: 14px;
    }
  }

}

.filter-tag-group {
  margin-right: 8px;
  color: #333;
  background-color: #EFF3FB;
  border-radius: 2px;
  ::v-deep .el-tag__close {
    color: #999;
  }
  ::v-deep .el-tag__close:hover {
    background-color: #ccc;
  }
}
.select-input-focus {
  &::v-deep {
    .el-input-group__prepend {
      border-color: var(--color-primary);
    }
  }
}
.time-type-select {
  & ::v-deep {
    .el-form-item__content {
      @include flexStyle($align: center)
    }
    .el-select {
      width: 100px;
      .el-input__inner {
        width: 105px !important;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: none;
        border-color: #DCDFE6 !important;
      }
    }
    .el-date-editor {
      width: 240px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      border-color: #DCDFE6 !important;
      .el-range-separator {
        width: 20px;
      }
    }
  }
}
.fliter-btn-container {
  %btn-common {
    padding: 0;
    border-radius: 4px;
    height: 32px;
  }
  .fliter-btn-container-search {
    width: 120px;
    @extend %btn-common;
  }
  .fliter-btn-container-clear {
    @extend %btn-common;
    width: 64px;
    color: #666;
    background:#fff;
    border: 1px solid #ddd
  }
}
.operate-btn {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 10px;
  @include flexStyle(center, center);
  &.active {
    background-color: #EDEEF2;
    border-radius: 4px;
  }
  .operate-icon {
    width: 16px;
    height: 16px;
  }
  .filter-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .filter-label {
      margin-top: 2px;
      font-size: 8px;
      color: #333;
    }
  }
}

</style>
